<template>
  <div>
    <van-cell @click="editClick(item)" v-for="item in Searchrecommend" :key="item" icon="search">
      <!-- v-html 后面可以处理span包裹的高亮效果 -->
      <div slot="title" v-html="formatStr(item)"></div>
    </van-cell>

  </div>
</template>

<script>
import { debounce } from 'lodash'
import { getSearchRecommend } from '@/api/search.js'
export default {
  data () {
    return {
      // 搜索推荐结果
      Searchrecommend: '',
      // 组件是否销毁
      isShow: true
    }
  },
  props: {
    value: {
      type: String,
      required: true
    }
  },
  // 监听父组件传过来的值是否改变
  watch: {
    value: {
      // 使用插件防抖
      handler: debounce(function (val) {
        if (!this.isShow) return
        this.locationsearch()
      }, 900),
      immediate: true
    }
  },
  methods: {
    // 点击搜索推荐把值传给父组件
    editClick (item) {
      this.$emit('search', item)
    },
    // 搜索推荐
    async locationsearch () {
      try {
        const { data: res } = await getSearchRecommend(this.value)
        this.Searchrecommend = res.data.options
        console.log(res)
      } catch (err) {
        this.$toast('获取失败')
      }
    },
    formatStr (item) {
      // 动态生成正则表达式
      const reg = new RegExp(this.value, 'gi')
      return item.replace(reg, '<span style="color:red">' + this.value + '</span>')
    }
  },
  beforeDestroy () {
    this.isShow = false
  }
}
</script>

<style>
</style>
